package com.daxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.*;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.base.vo.*;
import com.daxt.service.UserDeptServie;
import com.daxt.utils.file.PoiUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class UserDeptServiceImp implements UserDeptServie {
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ArchivesFondsMapper fondsMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private UserPostMapper userPostMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 导入部门
     *
     * @param deptUrl  文件地址
     * @return
     */
    @Override
    @Transactional
    public Result<String> parseUserDeptTemplate(String deptUrl) throws IOException {
        List<Dept> oneList = new ArrayList<>();
        InputStream downFile = new FileInputStream(deptUrl);
        Map<String, List<String>> importXLS = null;
        importXLS = PoiUtil.importXLSX(downFile, "Y");


        for (String key : importXLS.keySet()) {  //获取页数
            List<String> list = importXLS.get(key);  //获得每页的数据

            if("Sheet2".equals(key)){
                String oneDeptName="";    //一级部门
                String twoDeptName="";    //二级部门
                String threeDeptName="";  //三级部门
                String fourDeptName="";   //四级部门
                Long fondsId=0L;
                int l=1;
                int j=1;
                int k=1;
                Dept oneDept = new Dept();
                Dept twoDept = new Dept();
                Dept threeDept = new Dept();
                for (int li = 0; li < list.size(); li++) {
                    fourDeptName="";
                    String[] split = list.get(li).split("===");
                    for (int i=0;i<split.length;i++){
                        if(i==0 && !"".equals(split[i])) oneDeptName=split[i];
                        if(i==1 && !"".equals(split[i])) twoDeptName=split[i];
                        if(i==2 && !"".equals(split[i])) threeDeptName = split[i];
                        if(i==3 && !"".equals(split[i])) fourDeptName=split[i];
                    }

                    if(split.length==2){
                        threeDeptName="";
                    }
                    if(split.length==1){
                        threeDeptName="";
                        twoDeptName="";
                    }

                    //一级部门插入数据
                    if(!oneDeptName.equals(oneDept.getDeptName())){
                        if(fondsId==0L){
                            QueryWrapper<ArchivesFonds> queryWrapper=new QueryWrapper<>();
                            queryWrapper.eq("fondsName",oneDeptName.trim());
                            ArchivesFonds ArchivesFonds = fondsMapper.selectOne(queryWrapper);
                            if(ArchivesFonds==null){
                                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请先添加全宗！！！", null);
                            }
                            fondsId=ArchivesFonds.getId();
                        }

                        //给一级部门去重
                        QueryWrapper<Dept> oneDeptQueryWrapper =new QueryWrapper<>();
                        oneDeptQueryWrapper.eq("parentId","0");
                        oneDeptQueryWrapper.eq("deptName",oneDeptName);
                        List<Dept> oneDeptList= deptMapper.selectList(oneDeptQueryWrapper);
                        if(oneDeptList.size()<=0){
                            oneDept.setDeptName(oneDeptName);
                            oneDept.setFondsId(fondsId);
                            oneDept.setParentId(0L);
                            oneDept.setSort(1);

                            deptMapper.insert(oneDept);
                            oneDept.setPids(oneDept.getId()+"/");
                            oneDept.setDeptCode(oneDept.getId()+"");
                            oneDept.setPDeptCode(0+"");
                            deptMapper.updateById(oneDept);
                        }else{
                            oneDept=oneDeptList.get(0);
                        }




                    }

                    //二级部门插入数据
                    if(!"".equals(twoDeptName)&&!twoDeptName.equals(twoDept.getDeptName())){

                        //二级部门去重操作
                        QueryWrapper<Dept> twoDeptQueryWrapper =new QueryWrapper<>();
                        twoDeptQueryWrapper.eq("parentId",oneDept.getId());
                        twoDeptQueryWrapper.eq("deptName",twoDeptName);
                        List<Dept> twoDeptList= deptMapper.selectList(twoDeptQueryWrapper);
                        if(twoDeptList.size()<=0){
                            twoDept.setDeptName(twoDeptName);
                            twoDept.setFondsId(fondsId);
                            twoDept.setParentId(oneDept.getId());
                            twoDept.setSort(l);

                            deptMapper.insert(twoDept);
                            twoDept.setPids(oneDept.getId()+"/"+twoDept.getId()+"/");
                            twoDept.setDeptCode(twoDept.getId()+"");
                            twoDept.setPDeptCode(oneDept.getId()+"");
                            deptMapper.updateById(twoDept);
                            l++;
                            j=1;
                        }else{
                            twoDept=twoDeptList.get(0);
                        }


                    }

                    //三级部门插入数据
                    if(!"".equals(threeDeptName)&&!threeDeptName.equals(threeDept.getDeptName())){

                        //三级部门去重操作
                        QueryWrapper<Dept> threeDeptQueryWrapper =new QueryWrapper<>();
                        threeDeptQueryWrapper.eq("parentId",twoDept.getId());
                        threeDeptQueryWrapper.eq("deptName",threeDeptName);
                        List<Dept> threeDeptList= deptMapper.selectList(threeDeptQueryWrapper);
                        if(threeDeptList.size()<=0){
                            threeDept.setDeptName(threeDeptName);
                            threeDept.setFondsId(fondsId);
                            threeDept.setParentId(twoDept.getId());
                            threeDept.setSort(j);

                            deptMapper.insert(threeDept);
                            threeDept.setPids(oneDept.getId()+"/"+twoDept.getId()+"/"+threeDept.getId()+"/");
                            threeDept.setDeptCode(threeDept.getId()+"");
                            threeDept.setPDeptCode(twoDept.getId()+"");
                            deptMapper.updateById(threeDept);

                            j++;
                            k=1;
                        }else {
                            threeDept=threeDeptList.get(0);
                        }


                    }

                    //四级部门插入数据
                    if(!"".equals(fourDeptName)){
                        Dept fourDept=new Dept();

                        // 四级部门去重操作
                        QueryWrapper<Dept> fourDeptQueryWrapper =new QueryWrapper<>();
                        fourDeptQueryWrapper.eq("parentId",threeDept.getId());
                        fourDeptQueryWrapper.eq("deptName",fourDeptName);
                        List<Dept> fourDeptList= deptMapper.selectList(fourDeptQueryWrapper);
                        if(fourDeptList.size()<=0){
                            fourDept.setDeptName(fourDeptName);
                            fourDept.setFondsId(fondsId);
                            fourDept.setParentId(threeDept.getId());
                            fourDept.setSort(k);

                            deptMapper.insert(fourDept);
                            fourDept.setPids(oneDept.getId()+"/"+twoDept.getId()+"/"+threeDept.getId()+"/"+fourDept.getId()+"/");
                            fourDept.setDeptCode(fourDept.getId()+"");
                            fourDept.setPDeptCode(threeDept.getId()+"");
                            deptMapper.updateById(fourDept);
                            k++;
                        }


                    }
                }
            }

            if("Sheet1".equals(key)){
                for (int li = 0; li < list.size(); li++) {
                    String[] split = list.get(li).split("===");
                    String deptName=null;    //所属部门
                    String realName=null;    //姓名
                    String userName=null;    //登录名
                    String mobile=null;      //手机号
                    String postName=null;    //岗位
                    String roleName=null;    //角色
                    Long deptId=null;
                    List<Long> postId=new ArrayList<>();
                    Long roleId=null;
                    for (int i=0;i<split.length;i++){
                        if(i==0)deptName=split[i];
                        if(i==1)realName=split[i];
                        if(i==2)userName=split[i];
                        if(i==3)mobile=split[i];
                        if(i==4)postName=split[i];
                        if(i==5)roleName=split[i];
                    }

                    //去除重复的人员
                    QueryWrapper<BaseUser> baseUserQueryWrapper=new QueryWrapper<>();
                    baseUserQueryWrapper.eq("username",userName);
                    int count=userMapper.selectCount(baseUserQueryWrapper);
                    if(count>0) {
                        continue;
                    }

                    if(!StringUtils.isEmpty(deptName)){
                        String[] depts= deptName.split("-");
                        String oneDeptName=null;
                        String twoDeptName=null;
                        String threeDeptName=null;
                        String fourDeptName=null;
                        for (int i=0;i<depts.length;i++){
                            if(i==0 && !"".equals(depts[i])) oneDeptName=depts[i];
                            if(i==1 && !"".equals(depts[i])) twoDeptName=depts[i];
                            if(i==2 && !"".equals(depts[i])) threeDeptName = depts[i];
                            if(i==3 && !"".equals(depts[i])) fourDeptName=depts[i];
                        }

                        if(!StringUtils.isEmpty(oneDeptName)){
                            QueryWrapper<Dept> oneDeptWrapper=new QueryWrapper<>();
                            oneDeptWrapper.eq("deptName",oneDeptName);
                            Dept oneDept=deptMapper.selectOne(oneDeptWrapper);
                            if(oneDept==null){
                                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门:"+oneDeptName+"在系统中不存在，请先添加该部门！！！", null);
                            }
                            deptId=oneDept.getId();
                            if(!StringUtils.isEmpty(twoDeptName)){
                                QueryWrapper<Dept> twoDeptWrapper=new QueryWrapper<>();
                                twoDeptWrapper.eq("deptName",twoDeptName);
                                twoDeptWrapper.eq("parentId",oneDept.getId());
                                Dept twoDept=deptMapper.selectOne(twoDeptWrapper);
                                if(twoDept==null){
                                    return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门:"+twoDeptName+"在系统中不存在，请先添加该部门！！！", null);
                                }
                                deptId=twoDept.getId();
                                if(!StringUtils.isEmpty(threeDeptName)){
                                    QueryWrapper<Dept> threeDeptWrapper=new QueryWrapper<>();
                                    threeDeptWrapper.eq("deptName",threeDeptName);
                                    threeDeptWrapper.eq("parentId",twoDept.getId());
                                    Dept threeDept=deptMapper.selectOne(threeDeptWrapper);
                                    if(threeDept==null){
                                        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门:"+threeDeptName+"在系统中不存在，请先添加该部门！！！", null);
                                    }
                                    deptId=threeDept.getId();
                                    if(!StringUtils.isEmpty(fourDeptName)){
                                        QueryWrapper<Dept> fourDeptWrapper=new QueryWrapper<>();
                                        fourDeptWrapper.eq("deptName",fourDeptName);
                                        fourDeptWrapper.eq("parentId",threeDept.getId());
                                        Dept fourDept=deptMapper.selectOne(fourDeptWrapper);
                                        if(fourDept==null){
                                            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "部门:"+fourDeptName+"在系统中不存在，请先添加该部门！！！", null);
                                        }
                                        deptId=fourDept.getId();
                                    }
                                }
                            }
                        }
                    }

                    if (!StringUtils.isEmpty(postName)){
                        String[] postNames={postName};
                        if(postName.contains("、")){
                            postNames= postName.split("、");
                        }
                        QueryWrapper<Post> postWrapper=new QueryWrapper<>();
                        for (int i=0;i<postNames.length;i++){
                            postWrapper.eq("name",postNames[i]);
                            //当只有一个元素时不添加or
                            //当有多个元素时，最后一个元素后面不加or
                            if(postNames.length!=1 && i!=postNames.length-1){
                                postWrapper.or();
                            }
                        }

                        List<Post> listPost = postMapper.selectList(postWrapper);
                        if (listPost.size()<=0){
                           return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "岗位:"+postName+"在系统中不存在，请先添加该岗位！！！", null);
                        }
                        for(int i=0;i<listPost.size();i++){
                            postId.add(listPost.get(i).getId());
                        }
                    }
                    if (!StringUtils.isEmpty(roleName)){
                        QueryWrapper<Role> roleWrapper=new QueryWrapper<>();
                        roleWrapper.eq("name",roleName);
                        Role role = roleMapper.selectOne(roleWrapper);
                        if (role==null){
                            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "角色:"+roleName+"在系统中不存在，请先添加该角色！！！", null);
                        }
                        roleId=role.getId();
                    }

                    BaseUser user=new BaseUser();
                    user.setDeptIds(deptId);
                    user.setRealName(realName);
                    user.setUsername(userName);
                    user.setMobile(mobile);
                    user.setState("1");
                    user.setTenantId("00000000");
                    user.setPassword("e10adc3949ba59abbe56e057f20f883e");
                    user.setCreateTime(LocalDateTime.now());
                    userMapper.insert(user);

                    UserRole userRole=new UserRole();
                    userRole.setRoleId(roleId);
                    userRole.setUserId(user.getId());
                    userRoleMapper.insert(userRole);

                    UserDept userDept=new UserDept();
                    userDept.setUserId(user.getId());
                    userDept.setDeptId(deptId);
                    userDeptMapper.insert(userDept);

                    for(int i=0;i<postId.size();i++){
                        UserPost userPost=new UserPost();
                        userPost.setId(user.getId());
                        userPost.setPostId(postId.get(i));
                        userPostMapper.insert(userPost);
                    }
                }
            }

        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

}
